package com.enzoism.manual.springboot.config.shiro;

import com.enzoism.manual.springboot.model.User;
import com.enzoism.manual.springboot.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: SpringCloud
 * @description: 自定义用户声明
 * @author: zhifeng
 * @create: 2020-12-08 10:39
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);

    // 授权-用户的权限查询
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("-------------------------------------》用户授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 将数据库中的权限取出来
        User user = (User) principalCollection.getPrimaryPrincipal();
        info.addStringPermission(user.getPermes());
        return info;
    }

    // 证明-用户账密是否正确
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("-------------------------------------》用户认证doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.queryUserByName(token.getUsername());
        // TODO 添加空指针判断
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
